package com.ph.demo.cas;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 让普通元素也享受原子操作
 */
public class AtomicIntegerFiledUpdaterDemo {


    public static class Candidate{

        public int i;

        volatile int score;

    }
    public final static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");


    public static void main(String[] args) throws Exception{

        final Candidate candidate = new Candidate();

        AtomicInteger a = new AtomicInteger(0);

        Thread[] threads = new Thread[10000];

        for (int i = 0; i <10000 ; i++) {
            threads[i] = new Thread(){

                @Override
                public void run() {
                    if(Math.random()>0.4){

                        scoreUpdater.incrementAndGet(candidate);

                        a.incrementAndGet();
                    }
                }
            };
            threads[i].start();

        }

        for (int i = 0; i < 10000; i++) {
            threads[i].join();
        }

        System.out.println(candidate.score);
        System.out.println(a);

    }

}
